package model

import (
	"shortURL/pool"
	"time"
)

type Short struct {
	Id         int       `gorm:"primary_key"`
	LongUrl    string    `gorm:"column:long_url"`
	ShortUrl   string    `gorm:"column:short_url"`
	CreateTime time.Time `gorm:"column:create_time"`
}

func NewShort() *Short {
	return &Short{}
}

func (u *Short) TableName() string {
	return "short"
}

func (u *Short) Connect() string {
	return "default"
}

func (u *Short) Create() (id int, err error) {
	conn, err := pool.GetDbConn(u.Connect())
	if err != nil {
		return 0, err
	}
	defer pool.PutDbConn(u.Connect(), conn)

	if err := conn.Table(u.TableName()).Create(&u).Error; err != nil {
		return 0, err
	}

	return u.Id, nil
}

func FindUrLByShortUrl(shortUrl string) (short *Short, err error) {
	short = NewShort()

	conn, err := pool.GetDbConn(short.Connect())
	if err != nil {
		return nil, err
	}
	defer pool.PutDbConn(short.Connect(), conn)

	if conn.Table(short.TableName()).Where("short_url = ?", shortUrl).Find(&short).RecordNotFound() {
		return nil, nil
	}

	return short, nil
}
